using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

public class UI_EquipmentSlot : MonoBehaviour, IPointerClickHandler
{
    [SerializeField] private int _equipSlotNum;
    [SerializeField] private Image _equipSlotImage;
    private UI_BackPack _inventoryUI;
    public ItemDataSO _currentEquipedDataSO;
    private void Awake()
    {
        _inventoryUI = GetComponentInParent<UI_BackPack>();
    }
    public void SetupEquipmentUI(ItemDataSO itemDataSO)
    {
        _currentEquipedDataSO = itemDataSO;

        UpdateItemDtatSO();
    }
    
    public void UpdateItemDtatSO()
    {
        _equipSlotImage.sprite = _currentEquipedDataSO.itemIcon;
        _equipSlotImage.color = Color.white;
    }
    public void HiddleEquipSlot()
    {
        _equipSlotImage.color = Color.clear;

        _currentEquipedDataSO = null;
    }
    public void OnPointerClick(PointerEventData eventData)
    {
        ItemDataSO selectedEquipmentDataSO = _inventoryUI._selectedEquipmentDataSO;
        
        if (selectedEquipmentDataSO != null && _currentEquipedDataSO != null)
        {
            EventCenter.TriggerEvent(EventName.UI_CancelEquipment, _currentEquipedDataSO, _equipSlotNum);
            EventCenter.TriggerEvent(EventName.UI_EquipWeapon, selectedEquipmentDataSO, _equipSlotNum);

            SetupEquipmentUI(selectedEquipmentDataSO);

            _inventoryUI._selectedEquipmentDataSO = null;
        }
        else if(selectedEquipmentDataSO != null && _currentEquipedDataSO == null)
        {
            EventCenter.TriggerEvent(EventName.UI_EquipWeapon, selectedEquipmentDataSO, _equipSlotNum);

            SetupEquipmentUI(selectedEquipmentDataSO);
            
            _inventoryUI._selectedEquipmentDataSO = null;
        }
        else if (selectedEquipmentDataSO == null && _currentEquipedDataSO != null)
        {
            EventCenter.TriggerEvent(EventName.UI_CancelEquipment, _currentEquipedDataSO, _equipSlotNum);

            HiddleEquipSlot();
        }
        
    }

    public int GetCurrentSlotNum() => _equipSlotNum;
}
